<script setup lang="tsx">
import { businessRechargeApplyPageApi, businessRechargeApplyAuditApi } from '@/api/financial'
import type { MerchantListParams } from '@/api/BusinessManagement/types'
import { ElButton, ElMessageBox, ElImage } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { BusinessRechargeDict } from '@/utils/dict'

const { t } = useI18n()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await businessRechargeApplyPageApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      state: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '待审核',
    value: 1
  },
  {
    label: '审核通过',
    value: 3
  },
  {
    label: '驳回',
    value: 2
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'applyNo',
    label: '充值编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'keyword',
    label: '商家ID/名称',
    search: {
      componentProps: {
        placeholder: '请输入商家ID/名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 150,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.businessShortName}</div>
              <div class={'flex items-center'}>ID：{row.businessNo}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'paymentNo',
    label: '打款单号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'tradeAmt',
    label: '充值金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'paymentImage',
    label: '打款凭证',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>
                <ElImage
                  v-if={row.paymentImage}
                  src={row.paymentImage}
                  fit="cover"
                  class="w-15"
                  lazy
                  preview-src-list={[row.paymentImage]}
                  preview-teleported
                />
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'state',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.state && BusinessRechargeDict[row.state]}</div>
              {(row.state === 2 || row.state === 6) && (
                <div style="color: #F59A23;">
                  原因：{row.refuseReason ? row.refuseReason : '无'}
                </div>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'createTime',
    label: '提交时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'auditTime',
    label: '审核时间',
    form: {
      hidden: true
    },
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 200,
      slots: {
        default: (data: any) => {
          const row = data.row as MerchantListParams
          if (row.state === 1) {
            return (
              <>
                <ElButton
                  v-hasPermi="POST /businessRechargeApply/audit"
                  type="primary"
                  link
                  onClick={() => hanleAudit(row, 3)}
                >
                  通过
                </ElButton>
                <ElButton
                  v-hasPermi="POST /businessRechargeApply/audit"
                  type="primary"
                  link
                  onClick={() => hanleAudit(row, 2)}
                >
                  驳回
                </ElButton>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, auditTime, ...rest } = params
  let startCreateTime, endCreateTime, startAuditTime, endAuditTime
  if (createTime && createTime.length > 0) {
    startCreateTime = createTime[0]
    endCreateTime = createTime[1]
  }
  if (auditTime && auditTime.length > 0) {
    startAuditTime = auditTime[0]
    endAuditTime = auditTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    startCreateTime,
    endCreateTime,
    startAuditTime,
    endAuditTime,
    ...rest
  }
  getList()
}

const hanleAudit = async (row: any, i) => {
  if (i === 3) {
    ElMessageBox.confirm('确认通过该笔提现充值？')
      .then(async () => {
        const setData = {
          id: row.id,
          state: i
        }
        await businessRechargeApplyAuditApi(setData)
        currentPage.value = 1
        getList()
      })
      .catch(() => {
        console.log('取消')
      })
  } else {
    ElMessageBox.prompt('确认拒绝该笔充值？', {
      inputErrorMessage: '请填写拒绝理由'
    })
      .then(async ({ value }) => {
        const setData = {
          id: row.id,
          state: i,
          refuseReason: value
        }
        await businessRechargeApplyAuditApi(setData)
        currentPage.value = 1
        getList()
      })
      .catch(() => {
        console.log('取消')
      })
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>
  </div>
</template>
